package com.yzw.mybatisutils.uitls;

import com.yzw.mybatisutils.model.DataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author：yzw
 * @Date：2017/11/29
 * @描述：
 */
public class DataBaseUtil {

	private static final Map<String, String> JDBC_DRIVER_MAP = new HashMap<String, String>();
	private static final String DB_TYPE_MYSQL = "mysql";

	static {
		JDBC_DRIVER_MAP.put(DB_TYPE_MYSQL, "com.mysql.jdbc.Driver");
	}

	private static String buildURL(DataBase dataBase) {
		StringBuilder builder = new StringBuilder();
		if (DB_TYPE_MYSQL.equals(dataBase.getType())) {
			builder.append("jdbc:mysql://").append(dataBase.getIp()).append(":").append(dataBase.getPort()).append("/").append(dataBase.getDataBaseName());
			builder.append("?useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true&amp;useSSL=false");
		}
		return builder.toString();
	}

	public static Connection getConnection(DataBase dataBase) throws ClassNotFoundException, SQLException {
		String url = buildURL(dataBase);
		Class.forName(JDBC_DRIVER_MAP.get(dataBase.getType()));
		return DriverManager.getConnection(url, dataBase.getUserName(), dataBase.getPassword());
	}
}
